using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System.Xml;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Timers;

using MediaPortal.GUI.Library;
using MediaPortal.Dialogs;
using MediaPortal.Util;
using MediaPortal.Localisation;
using MediaPortal.Configuration;
using MediaPortal.Player;
using MediaPortal.Playlists;



namespace MTVMusicPlugin
{
  public class MTVMusicGUI : MTVMusicGUIBase, ISetupForm 
  {

    #region MapSettings class
    [Serializable]
    public class MapSettings
    {
      protected int _SortBy;
      protected int _ViewAs;
      protected bool _SortAscending;

      public MapSettings()
      {
        // Set default view
        _SortBy = 0;
        _ViewAs = (int)View.List;
        _SortAscending = true;
      }

      [XmlElement("SortBy")]
      public int SortBy
      {
        get { return _SortBy; }
        set { _SortBy = value; }
      }

      [XmlElement("ViewAs")]
      public int ViewAs
      {
        get { return _ViewAs; }
        set { _ViewAs = value; }
      }

      [XmlElement("SortAscending")]
      public bool SortAscending
      {
        get { return _SortAscending; }
        set { _SortAscending = value; }
      }
    }
    #endregion

    #region Base variables

    #endregion

    enum View
    {
      List = 0,
      Icons = 1,
      BigIcons = 2,
      Albums = 3,
      PlayList = 4,
      Filmstrip = 5
    }

    #region locale vars

    private WebClient Client = new WebClient();
    private Queue downloaQueue = new Queue();
    private Stack NavigationStack = new Stack();
    private System.Timers.Timer updateStationLogoTimer = new System.Timers.Timer(1 * 1000);
    private DownloadFileObject curentDownlodingFile;
    MapSettings mapSettings = new MapSettings();

    private MTVService service = new MTVService();

    private char[] startCharacters = { '-', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };


    #endregion

    #region skin connection
    [SkinControlAttribute(50)]
    protected GUIFacadeControl listControl = null;
    //[SkinControlAttribute(2)]
    //protected GUISortButtonControl sortButton = null;
    [SkinControlAttribute(4)]
    protected GUIButtonControl homeButton = null;
    [SkinControlAttribute(3)]
    protected GUIButtonControl btnSwitchView = null;
    [SkinControlAttribute(2)]
    protected GUIButtonControl searchButton = null;
    [SkinControlAttribute(6)]
    protected GUIButtonControl searchArtistButton = null;
    [SkinControlAttribute(7)]
    protected GUIButtonControl btnPlayList = null;
    [SkinControlAttribute(8)]
    protected GUIButtonControl btnNowPlaying = null;

    #endregion


    public MTVMusicGUI()
    {
      _setting.Load();
      GetID = GetWindowId();
      updateStationLogoTimer.AutoReset = true;
      updateStationLogoTimer.Enabled = false;
      updateStationLogoTimer.Elapsed += new ElapsedEventHandler(OnDownloadTimedEvent);
      Client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadLogoEnd);
      GUIWindowManager.Receivers += new SendMessageHandler(GUIWindowManager_Receivers);
 
    }

    void GUIWindowManager_Receivers(GUIMessage message)
    {
    }

    #region ISetupForm Members
    // return name of the plugin
    public string PluginName()
    {
      return _setting.PluginName;
    }
    // returns plugin description
    public string Description()
    {
      return "Plugin for expose the MTV Music contents";
    }
    // returns author
    public string Author()
    {
      return "Dukus";
    }
    // shows the setup dialog
    public void ShowPlugin()
    {
      SetupForm setup = new SetupForm();
      setup._settings = _setting;
      setup.ShowDialog();
    }
    // enable / disable
    public bool CanEnable()
    {
      return true;
    }
    // returns the unique id again
    public int GetWindowId()
    {
      return 28050;
    }
    // default enable?
    public bool DefaultEnabled()
    {
      return true;
    }
    // has setup gui?
    public bool HasSetup()
    {
      return true ;
    }
    // home button
    public bool GetHome(out string strButtonText, out string strButtonImage,
      out string strButtonImageFocus, out string strPictureImage)
    {
      // set the values for the buttom
      strButtonText = _setting.PluginName;

      // no image or picture
      strButtonImage = String.Empty;
      strButtonImageFocus = String.Empty;
      strPictureImage = String.Empty;

      return true;
    }
    // init the skin
    public override bool Init()
    {
      return Load(GUIGraphicsContext.Skin + @"\mtvmusicmain.xml");
    }

    void provider_OnError(Exception ex)
    {
      
    }
     //do the init before page load
    protected override void OnPageLoad()
    {
      updateStationLogoTimer.Enabled = true;
      GUIPropertyManager.SetProperty("#nowplaying", " ");
      if (MessageGUI.Item != null)
      {

      }
      else
      {
        if (NavigationStack.Count == 0)
        {
          ClearLabels("Curent");
          ClearLabels("NowPlaying");
          GUIPropertyManager.SetProperty("#header.label", GUILocalizeStrings.Get(128052));
          InitList(_setting.InitialDisplay);
        }
        else
        {
          DoBack();
          GUIControl.FocusControl(GetID, listControl.GetID);
        }
      }
      base.OnPageLoad();
    }

    private void InitList(int state)
    {
      GUIControl.ClearControl(GetID, listControl.GetID);
      if (state == 0)
      {
        for (int i = 0; i < startCharacters.Length; i++)
        {
          GUIListItem item = new GUIListItem();
          item.Label = string.Format("#{0}", startCharacters[i].ToString());
          item.IsFolder = true;
          MediaPortal.Util.Utils.SetDefaultIcons(item);
          item.MusicTag = startCharacters[i].ToString();
          listControl.Add(item);
        }
      }
      if (state == 1)
      {
        foreach(GenreEntity ge in service.Genres)
        {
          GUIListItem item = new GUIListItem();
          item.Label = ge.DisplayName;
          item.IsFolder = true;
          MediaPortal.Util.Utils.SetDefaultIcons(item);
          item.MusicTag = ge;
          listControl.Add(item);
        }
      }
    }
    // remeber the selection on page leave
    protected override void OnPageDestroy(int new_windowId)
    {
      SaveListState(false);
      base.OnPageDestroy(new_windowId);
    }
    //// do the clicked action
    protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
    {
      ////
      //// look for button pressed
      ////
      //// record ?
      if (actionType == Action.ActionType.ACTION_RECORD)
      {
        //ExecuteRecord();
      }
      else if (control == btnSwitchView)
      {
        switch ((View)mapSettings.ViewAs)
        {
          case View.List:
            mapSettings.ViewAs = (int)View.Icons;
            break;
          case View.Icons:
            mapSettings.ViewAs = (int)View.BigIcons;
            break;
          case View.BigIcons:
            mapSettings.ViewAs = (int)View.Albums;
            break;
          case View.Albums:
            mapSettings.ViewAs = (int)View.Filmstrip;
            break;
          case View.Filmstrip:
            mapSettings.ViewAs = (int)View.List;
            break;
        }
        ShowPanel();
        GUIControl.FocusControl(GetID, control.GetID);
      }
      else if (control == listControl)
      {
        // execute only for enter keys
        if (actionType == Action.ActionType.ACTION_SELECT_ITEM)
        {
          // station selected
          DoListSelection();
        }
      }
      //else if (control == sortButton)
      //{
      //  //sort button selected
      //  OnShowSortOptions();
      //}
      else if (control == searchButton)
      {
        DoSearch();
        GUIControl.FocusControl(GetID, listControl.GetID);
      }
      else if (control == homeButton)
      {
        DoHome();
        GUIControl.FocusControl(GetID, listControl.GetID);
      }
      else if (control == searchArtistButton)
      {
        DoSearchArtist();
        GUIControl.FocusControl(GetID, listControl.GetID);
      }
      else if (control == btnPlayList)
      {
        GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_VIDEO_PLAYLIST);
      }
      else if (control == btnNowPlaying)
      {
        GUIWindowManager.ActivateWindow(27052);
      }
      base.OnClicked(controlId, control, actionType);
    }

    private void DoSearchArtist()
    {
      string searchString = "";

      // display an virtual keyboard
      VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_VIRTUAL_KEYBOARD);
      if (null == keyboard) return;
      keyboard.Reset();
      keyboard.Text = searchString;
      keyboard.DoModal(GetWindowId());
      if (keyboard.IsConfirmed)
      {
        // input confirmed -- execute the search
        searchString = keyboard.Text;
      }

      if ("" != searchString)
      {
        MTVArtistResponse resp = service.ArtistSearch(searchString, 0, 0);
        if (resp.Items.Count > 0)
        {
          SaveListState(true);
          addArtists(resp);
          UpdateGui();
        }
        else
        {
          Err_message(127086);
        }
      }
    }


    private void DoHome()
    {
      GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
      if (dlg == null) return;
      dlg.Reset();
      //dlg.SetHeading(25653); // Sort options

      dlg.Add("Alphabetical Index"); 
      dlg.Add("Genres");
      //// set the focus to currently used sort method
      //dlg.SelectedLabel = (int)curSorting;

      // show dialog and wait for result
      dlg.DoModal(GetID);
      if (dlg.SelectedId == -1) return;

      switch (dlg.SelectedLabel)
      {
        case 0:
          InitList(0);
          break;
        case 1:
          InitList(1);
          break;
      }
    }


    //// override action responses
    public override void OnAction(Action action)
    {
      if (action.wID == Action.ActionType.ACTION_PREVIOUS_MENU)
      {
        if (listControl.Focus)
        {
          if (NavigationStack.Count > 0)
          {
            DoBack();
            return;
          }
        }
      }

      if (action.wID == Action.ActionType.ACTION_PARENT_DIR)
      {
        GUIListItem item = listControl[0];
        
        if ((item != null) && item.IsFolder && (item.Label == ".."))
        {
          DoBack();
          return;
        }
      }
      UpdateGui();
      base.OnAction(action);
    }
    // do regulary updates
    public override void Process()
    {
      // update the gui
      UpdateGui();
    }

    protected void OnShowSortOptions()
    {
    }
 
    #endregion
    #region helper func's

    private void DoListSelection()
    {
      GUIWaitCursor.Show();
      GUIListItem selectedItem = listControl.SelectedListItem;
      if (selectedItem != null)
      {
        if (selectedItem.Label != "..")
        {
          //--------------------
          string leter = selectedItem.MusicTag as string;
          if (leter != null)
          {
            SaveListState(true);
            MTVArtistResponse resp = service.ArtistBrowse(leter);
            addArtists(resp);
          }
          ArtistEntry art = selectedItem.MusicTag as ArtistEntry;
          if (art != null)
          {
            SaveListState(true);
            MTVVideoResponse vid = service.Video(art.VideosUrl);
            addVideos(vid, false);
          }
          VideoEntry vide = selectedItem.MusicTag as VideoEntry;
          if (vide != null)
          {
            DoPlay(vide);
          }
          GenreEntity cat = selectedItem.MusicTag as GenreEntity;
          if (cat != null)
          {
            SaveListState(true);
            GUIListItem item = new GUIListItem();
            item.Label = "Artists";
            item.IsFolder = true;
            MediaPortal.Util.Utils.SetDefaultIcons(item);
            item.MusicTag = new ArtistCatEntry(cat);
            listControl.Add(item);
            
            GUIListItem item1 = new GUIListItem();
            item1.Label = "Videos";
            item1.IsFolder = true;
            MediaPortal.Util.Utils.SetDefaultIcons(item1);
            item1.MusicTag = new VideoCatEntry(cat);
            listControl.Add(item1);
          }
          ArtistCatEntry artistcat = selectedItem.MusicTag as ArtistCatEntry;
          if (artistcat != null)
          {
            SaveListState(true);
            MTVArtistResponse resp = service.Artist(artistcat.Url);
            addArtists(resp);
          }

          VideoCatEntry videocat = selectedItem.MusicTag as VideoCatEntry;
          if (videocat != null)
          {
            SaveListState(true);
            MTVVideoResponse vid = service.Video(videocat.Url);
            addVideos(vid, false);
          }
        }
        else
        {
          DoBack();
        }
      }
      GUIWaitCursor.Hide();
      //throw new Exception("The method or operation is not implemented.");
    }

    private void DoSearch()
    {
      string searchString = "";

      // display an virtual keyboard
      VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_VIRTUAL_KEYBOARD);
      if (null == keyboard) return;
      keyboard.Reset();
      keyboard.Text = searchString;
      keyboard.DoModal(GetWindowId());
      if (keyboard.IsConfirmed)
      {
        // input confirmed -- execute the search
        searchString = keyboard.Text;
      }

      if ("" != searchString)
      {
        MTVVideoResponse vidr = service.VideoSearch(searchString, 0, 0);
        if (vidr.Items.Count > 0)
        {
          SaveListState(true);
          addVideos(vidr, false);
          UpdateGui();
        }
        else
        {
          Err_message(128086);
        }
      }
    }
    
    private void DoBack()
    {
      if (NavigationStack.Count > 0)
      {
        GUIControl.ClearControl(GetID, listControl.GetID);
        NavigationObject obj = NavigationStack.Pop() as NavigationObject;
        obj.SetItems(listControl);
        listControl.SelectedListItemIndex = obj.Position;
        GUIPropertyManager.SetProperty("#header.label", obj.Title);
      }
    }
    
    //public void UpdateList()
    //{
   
    //}

    void ShowPanel()
    {
      int itemIndex = listControl.SelectedListItemIndex;
      if (mapSettings.ViewAs == (int)View.BigIcons)
      {
        listControl.View = GUIFacadeControl.ViewMode.LargeIcons;
      }
      else if (mapSettings.ViewAs == (int)View.Albums)
      {
        listControl.View = GUIFacadeControl.ViewMode.AlbumView;
      }
      else if (mapSettings.ViewAs == (int)View.Icons)
      {
        listControl.View = GUIFacadeControl.ViewMode.SmallIcons;
      }
      else if (mapSettings.ViewAs == (int)View.List)
      {
        listControl.View = GUIFacadeControl.ViewMode.List;
      }
      else if (mapSettings.ViewAs == (int)View.Filmstrip)
      {
        listControl.View = GUIFacadeControl.ViewMode.Filmstrip;
      }
      else if (mapSettings.ViewAs == (int)View.PlayList)
      {
        listControl.View = GUIFacadeControl.ViewMode.Playlist;
      }

      if (itemIndex > -1)
      {
        GUIControl.SelectItemControl(GetID, listControl.GetID, itemIndex);
      }
     
    }

    /// <summary>
    /// Called when [show context menu].
    /// </summary>
    protected override void OnShowContextMenu()
    {
      GUIListItem selectedItem = listControl.SelectedListItem;
      VideoEntry vidItem = null;
      ArtistEntry artItem=null;
      GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
      if (dlg == null)
        return;
      dlg.Reset();
      dlg.SetHeading(498); // menu
      string gurl = "";

      if (selectedItem != null)
      {
        vidItem = selectedItem.MusicTag as VideoEntry;
        artItem = selectedItem.MusicTag as ArtistEntry;
        if (vidItem != null)
        {
          //dlg.AddLocalizedString(127075); // info
          dlg.AddLocalizedString(128082);// add to playlist
          dlg.AddLocalizedString(128080);// all videos from artis
          dlg.AddLocalizedString(128084); // similar artist
          if (!string.IsNullOrEmpty(vidItem.Genre))
            dlg.Add(string.Format("Artists & videos for {0} genre", vidItem.Genre));
          gurl = vidItem.GenreUrl;
        }
        
        if(artItem!=null)
        {
            dlg.AddLocalizedString(128084); // similar artist
            if (!string.IsNullOrEmpty(artItem.Genre))
              dlg.Add(string.Format("Artists & videos for {0} genre", artItem.Genre));
            gurl = artItem.GenreUrl;
        }
      }

      dlg.DoModal(GetID);
      if (dlg.SelectedId == -1)
        return;

      if (dlg.SelectedLabelText.StartsWith("Artists & videos for"))
      {
        SaveListState(true);
        GUIListItem item = new GUIListItem();
        item.Label = "Artists";
        item.IsFolder = true;
        MediaPortal.Util.Utils.SetDefaultIcons(item);
        item.MusicTag = new ArtistCatEntry(gurl + "artists/");
        listControl.Add(item);

        GUIListItem item1 = new GUIListItem();
        item1.Label = "Videos";
        item1.IsFolder = true;
        MediaPortal.Util.Utils.SetDefaultIcons(item1);
        item1.MusicTag = new VideoCatEntry(gurl + "videos/");
        listControl.Add(item1);
        GUIPropertyManager.SetProperty("#header.label", dlg.SelectedLabelText);
      }
      switch (dlg.SelectedId)
      {
        case 127075: //info
          DoInfo();
          break;
        case 128080: // all videos from artis
          {
            MTVArtistResponse resp = service.Artist(vidItem.ArtistUrl);
            MTVVideoResponse visresp = service.Video(resp.Items[0].VideosUrl);
            if (visresp.Items.Count > 0)
            {
              SaveListState(true);
              addVideos(visresp,true);
            }
            else
            {
              Err_message(128086);
            }

          }
          break;
        case 128082: //add to playlist
          AddItemToPlayList(selectedItem);
          break;
        case 128084: // similar artist
          {
            if (artItem != null)
            {
              MTVArtistResponse similaart = service.Artist(artItem.RelatatedUrl);
              if (similaart.Items.Count > 0)
              {
                SaveListState(true);
                addArtists(similaart);
              }
              else
              {
                Err_message(128086);
              }
            }
            else
            {
              MTVArtistResponse resp = service.Artist(vidItem.ArtistUrl);
              MTVArtistResponse similaart = service.Artist(resp.Items[0].RelatatedUrl);
              if (similaart.Items.Count > 0)
              {
                SaveListState(true);
                addArtists(similaart);
              }
              else
              {
                Err_message(128086);
              }
            }
          }
          break;
        case 127085:  // similar videos
          {

          }
          break;
        case 127089:  // add to favorites
          {
            //UserFavoriteVideosService fav = new UserFavoriteVideosService();
            //fav.Ymid = provider.CurentUser.Ymid;
            //fav.Ids = vidItem.Video.Id;
            //provider.PostData(fav);

          }
          break;
        case 127093:  // add to favorites
          {
            
          }
          break;
      }
    }

    private void DoInfo()
    {
      //YahooMusicInfoGUI guiInfo = (YahooMusicInfoGUI)GUIWindowManager.GetWindow(27051);
      //guiInfo.InfoItem = listControl.SelectedListItem.MusicTag as VideoResponse;
      //guiInfo.provider = this.provider;
      //GUIWindowManager.ActivateWindow(27051);
    }

    /// <summary>
    /// Does the option.
    /// </summary>
    private void DoOption()
    {
      GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
      if (dlg == null)
        return;
      dlg.Reset();
      dlg.SetHeading(127073); // menu
      dlg.DoModal(GetID);
      if (dlg.SelectedId == -1)
        return;
    }

    /// <summary>
    /// Adds to favorites.
    /// </summary>
    /// <param name="p">The station id.</param>
    private void AddToFavorites(int p)
    {
      //try
      //{
      //  FavoriteFolderUpdateRequest req = new FavoriteFolderUpdateRequest();
      //  req.ItemIds = new int[] { p };
      //  req.Identification = iden;
      //  websrv.Favorite_StationListAdd(req);
      //  grabber.GetData(grabber.CurentUrl, grabber.CacheIsUsed, false);
      //  UpdateList();
      //}
      //catch (Exception)
      //{
      //  Err_message(25659);
      //}
    }

    public void UpdateGui()
    {

      string textLine = string.Empty;
      View view = (View)mapSettings.ViewAs;
      bool sortAsc = mapSettings.SortAscending;
      switch (view)
      {
        case View.List:
          textLine = GUILocalizeStrings.Get(101);
          break;
        case View.Icons:
          textLine = GUILocalizeStrings.Get(100);
          break;
        case View.BigIcons:
          textLine = GUILocalizeStrings.Get(417);
          break;
        case View.Albums:
          textLine = GUILocalizeStrings.Get(529);
          break;
        case View.Filmstrip:
          textLine = GUILocalizeStrings.Get(733);
          break;
        case View.PlayList:
          textLine = GUILocalizeStrings.Get(101);
          break;

      }
      GUIControl.SetControlLabel(GetID, btnSwitchView.GetID, textLine);

    }

    void SortChanged(object sender, SortEventArgs e)
    {
      // save the new state
      mapSettings.SortAscending = e.Order != System.Windows.Forms.SortOrder.Descending;
      // update the list
      //UpdateList();
      //UpdateButtonStates();
      GUIControl.FocusControl(GetID, ((GUIControl)sender).GetID);
    }

    #endregion

    #region download manager



    private string DownloadImage(string Url)
    {
      //string localFile = GetLocalImageFileName(Url);
      //if (!File.Exists(localFile) && !string.IsNullOrEmpty(Url))
      //{
      //  downloaQueue.Enqueue(new DownloadFileObject(localFile, Url));
      //}
      return DownloadImage(Url, null);
    }

    private string DownloadImage(string Url, string localFile,GUIListItem item)
    {
      if (!File.Exists(localFile) && !string.IsNullOrEmpty(Url))
      {
        downloaQueue.Enqueue(new DownloadFileObject(localFile, Url, item));
      }
      return localFile;
    }

    private string DownloadImage(string Url, GUIListItem listitem)
    {
      string localFile = GetLocalImageFileName(Url);
      if (!File.Exists(localFile) && !string.IsNullOrEmpty(Url))
      {
        downloaQueue.Enqueue(new DownloadFileObject(localFile, Url, listitem));
      }
      return localFile;
    }
    
    private void OnDownloadTimedEvent(object source, ElapsedEventArgs e)
    {
      if (!Client.IsBusy && downloaQueue.Count>0)
      {
        curentDownlodingFile = (DownloadFileObject)downloaQueue.Dequeue();
        Client.DownloadFileAsync(new Uri(curentDownlodingFile.Url), Path.GetTempPath() + @"\station.png");
      }
    }

    private void DownloadLogoEnd(object sender, AsyncCompletedEventArgs e)
    {
      if (e.Error == null)
      {
        File.Copy(Path.GetTempPath() + @"\station.png", curentDownlodingFile.FileName, true);
        if (curentDownlodingFile.ListItem != null && File.Exists(curentDownlodingFile.FileName))
        {
          curentDownlodingFile.ListItem.ThumbnailImage = curentDownlodingFile.FileName;
          curentDownlodingFile.ListItem.IconImageBig = curentDownlodingFile.FileName;
          curentDownlodingFile.ListItem.RefreshCoverArt();
        }
        UpdateGui();
      }
    }            

    #endregion

   
    void addArtists(MTVArtistResponse artists)
    {
      updateStationLogoTimer.Enabled = false;
      downloaQueue.Clear();
      foreach (ArtistEntry ae in artists.Items)
      {
        GUIListItem item = new GUIListItem();
        // and add station name & bitrate
        item.Label = ae.Entry.Author.Name;
        item.Label2 = "";
        item.IsFolder = true;
        string imageFile = GetLocalImageFileName(ae.Entry.Thumbnail.Url);
        if (File.Exists(imageFile))
        {
          item.ThumbnailImage = imageFile;
          item.IconImage = "DefaultFolderBig.png";
          item.IconImageBig = imageFile;
        }
        else
        {
          MediaPortal.Util.Utils.SetDefaultIcons(item);
          DownloadImage(ae.Entry.Thumbnail.Url, item);
        }
        item.MusicTag = ae;
        listControl.Add(item);
      }
      if (artists.Feed.StartIndex + artists.Feed.ItemsPerPage < artists.Feed.TotalResults)
      {
        GUIListItem item = new GUIListItem();
        // and add station name & bitrate
        item.Label = string.Format("Next Page {0} - {1} (2)", artists.Feed.StartIndex + artists.Feed.ItemsPerPage + 1, artists.Feed.StartIndex + 1 + artists.Feed.ItemsPerPage * 2, artists.Feed.TotalResults);
        item.Label2 = "";
        item.IsFolder = true;
        MediaPortal.Util.Utils.SetDefaultIcons(item);
        item.MusicTag = new ArtistCatEntry(artists, artists.Feed.StartIndex + artists.Feed.ItemsPerPage + 1, artists.Feed.ItemsPerPage);
        listControl.Add(item);
      }
      GUIPropertyManager.SetProperty("#header.label", artists.Feed.Title.Content);
      UpdateGui();
      updateStationLogoTimer.Enabled = true; 
    }

   void addVideos(MTVVideoResponse videos, bool level)
    {
      if (level)
      {
        GUIListItem item = new GUIListItem();
        item.Label = "..";
        item.IsFolder = true;
        MediaPortal.Util.Utils.SetDefaultIcons(item);
        listControl.Add(item);
      }
      GUIPropertyManager.SetProperty("#header.label", videos.Feed.Title.Content);
      updateStationLogoTimer.Enabled = false;
      downloaQueue.Clear();
      foreach (VideoEntry ae in videos.Items)
      {
        GUIListItem item = new GUIListItem();
        // and add station name & bitrate
        item.Label = ae.Entry.Author.Name + " - " + ae.Entry.Title.Content;
        item.Label2 = "";
        item.IsFolder = false;
        string imageFile = GetLocalImageFileName(ae.Entry.Thumbnail.Url);
        if (File.Exists(imageFile))
        {
          item.ThumbnailImage = imageFile;
          item.IconImage = "defaultVideoBig.png";
          item.IconImageBig = imageFile;
        }
        else
        {
          MediaPortal.Util.Utils.SetDefaultIcons(item);
          DownloadImage(ae.Entry.Thumbnail.Url, item);
        }
        item.MusicTag = ae;
        listControl.Add(item);
      }
      if (videos.Feed.StartIndex + videos.Feed.ItemsPerPage < videos.Feed.TotalResults)
      {
        GUIListItem item = new GUIListItem();
        // and add station name & bitrate
        item.Label = string.Format("Next Page {0} - {1} ({2})", videos.Feed.StartIndex + videos.Feed.ItemsPerPage + 1, videos.Feed.StartIndex + 1 + videos.Feed.ItemsPerPage * 2, videos.Feed.TotalResults);
        item.Label2 = "";
        item.IsFolder = true;
        MediaPortal.Util.Utils.SetDefaultIcons(item);
        item.MusicTag = new VideoCatEntry(videos, videos.Feed.StartIndex + videos.Feed.ItemsPerPage + 1, videos.Feed.ItemsPerPage);
        listControl.Add(item);

      }
      GUIPropertyManager.SetProperty("#header.label", videos.Feed.Title.Content);
      UpdateGui();
      updateStationLogoTimer.Enabled = true;
    }

    private void item_OnItemSelected(GUIListItem item, GUIControl parent)
    {
      VideoEntry vid = item.MusicTag as VideoEntry;
      if (vid != null)
      {
        if (File.Exists(Utils.GetLargeCoverArtName(Thumbs.MusicArtists, vid.Entry.Author.FullName)))
        {
          listControl.FilmstripView.InfoImageFileName = Utils.GetLargeCoverArtName(Thumbs.MusicArtists, vid.Entry.Author.FullName);
        }
        else
        {
          listControl.FilmstripView.InfoImageFileName = GetLocalImageFileName(vid.Entry.Thumbnail.Url);
        }
        SetLabels(vid, "Curent");
      }
    }

    private void SaveListState(bool clear)
    {
      if (listControl.ListView.ListItems.Count > 0)
      {
        NavigationStack.Push(new NavigationObject(listControl.ListView, GUIPropertyManager.GetProperty("#header.label"), listControl.SelectedListItemIndex));
      }
      if (clear)
      {
        GUIControl.ClearControl(GetID, listControl.GetID);
      }
    }
    

  }
}
